var product = {};
product.Plan = {};
product.addLog=function(message,code,ctx){
	$.get(ctx+"/report/log/addLog.jspx",{format:"json",m:message,c:code},function(data){
		
	});
};
product.Plan.listInit = function(){
	product.Plan.initGrid();
};
product.Plan.initGrid = function(){
	var options = {},
        colNames = ["","序号","计划编号","物料编号","规格","数量","单位","状态","计划完成时间","实际完成时间","紧急<br/>状态","添加人"];
        colModel = [
        {name:"myac",fixed:true,width:55,sortable:false,align:'center',formatter:product.Plan.customActions,formatoptions:{
            keys:true,
            editformbutton:false,
            editUrl:"preEdit.jspx?id=",
            delUrl:"delete.jspx?id="}
        },
        {name:"id",index:"id",width:50,fixed:true,align:'center',key:true},
        {name:"code",index:"code",width:18},
        {name:"materialCode",index:"materialCode",width:18},
        {name:"materialModel",index:"materialModel",width:25,sortable:false},
        {name:"planNum",index:"planNum",width:12},
        {name:"unit",index:"unit",width:10,sortable:false},
        {name:"statusMessage",index:"status",width:20,align:'center',formatter:product.Plan.showStatus},
        {name:"finishDate",index:"finishDate",width:20,align:'center'},
        {name:"edittime",index:"edittime",width:25},
        {name:"typeMessage",index:"type",width:8,align:'center',formatter:function(cellValue,options,rowObject){
        	if(cellValue=='紧急'){
        		return '<span style="color:red;font-weight:bold">紧急</span>';
        	}else{
        		return cellValue;
        	}
        }},
        {name:"inputer",index:"inputer",width:25}
    ];
    options = {colNames:colNames,
               colModel:colModel,
               newUrl:"preAdd.jspx",
               editUrl:"preEdit.jspx?id=",
               delUrl:"del.jspx?id=",
               canEdit:false,
               canAdd:false,
               canDel:false,
               caption:"生产计划列表"};
    
    customGrid.init(options);
};

product.Plan.customActions = function(cellValue,options,rowObject){
	var id = options.rowId,
		show = "<a href=\"../plan_detail/listBy.jspx?id="+id+"\" title='查看计划详情'>查看</a>";
	
	return show;
};
product.Plan.showStatus = function(cellValue,options,rowObject){
	var status = rowObject.status;
	if('Finish'==status){
		return '<span style="color:green">'+cellValue+'</span>';
	}else if('NoFinish'==status){
		return cellValue;
	}else{
		return '<button class="btn btn-primary btn-sm" onclick="product.Plan.stockIn('+options.rowId+')">检验并入库</button>';
	}
};

product.Plan.stockIn = function(planId){
	$.get('getOne.jspx?format=json',{id:planId},function(data){
		if(data!==undefined){
			if(data.hasError!==undefined && data.hasError==false){
				var templateData = template('plan-stockIn-template-body',data);
				$('#plan-stockIn-body').empty().append(templateData);
				$('#plan_id').val(planId);
				$('#plan-stockIn-modal').modal();
			}else{
				alert(data.message);
			}
		}
	});
	
};
product.Plan.submitStockIn = function(ctx){
	var result = confirm("确定要入库吗?");
	if(result){
		var $form=$("#plan_stockIn_form");
		var requestData = $form.formSerialize();
		console.log(requestData);
		$.get('submitStockIn.jspx?format=json&'+requestData,function(data){
			if(data!==undefined && data.hasError===false){
				$("#plan-stockIn-modal").modal("hide");
				$("#plan_id").val(0);
				customGrid.reload({url:'getJson.jspx?format=json'});
			}else{
				alert(data.message);
			}
		});
		product.addLog("提交入库信息","007",ctx);
	}else{
		product.addLog("取消提交入库信息","007",ctx);
	}
};

product.Plan.ctx = {};
product.Plan.setCtx = function(ctx){
	product.Plan.ctx = ctx;
};
product.Plan.getCtx = function(){
	return product.Plan.ctx;
};
product.Plan.autoModel = function(container){
	var ctx = product.Plan.getCtx();
	$(container).autocomplete({
		serviceUrl:ctx+"/repo/material/listAutoModel.jspx?format=json&action=code",
		formatResult:function(suggestion,currentValue){
			return suggestion.value+" - "+suggestion.data;
		},
		width:400,
	    onSelect:function(suggestion){
	    	var lastCode = $("#last_code").val();
		   var code = suggestion.value;
		   console.debug(lastCode+" "+code);
		   var $this=$(this);
		   if(code!==undefined){
			   var $a = $("#find_stock");
			   if($a!==undefined){
				   $a.css("display","");
				   var url = ctx+"/report/material/findBomStock.jspx?code="+code;
				   $a.attr("href",url);
				   $a.text("查看["+code+"]库存");
			   }
			   if(lastCode!==undefined && lastCode!==code){
				   product.Plan.getBom(code,ctx);
			   }
		   }
		   $("#last_code").val(code);
	    }
		
	});
};
product.Plan.getBom=function(code,ctx){
	var index = $("#current_id").val();
	$.get(ctx+"/repo/material/getOne.jspx",{format:"json",code:code,action:"hasBom"},function(data){
		   if(data!==undefined){
			   if(data.hasBom!==undefined && data.hasBom===false){
				   alert(code+"：物料的BOM信息无法找到，请更新BOM信息后再添加此生产计划");
				   return;
			   }else{
				   $("#model_"+index).val(data.material.model+" "+data.material.specification);
				   $("#color_"+index).val(data.material.color);
				   if(data.hasSubBom!==undefined && data.hasSubBom===true){
					   console.debug(data.subBomCodeList);
					   $.each(data.subBomCodeList,function(index,code){
						   product.Plan.addDetail(code);
						   var sub_currentId=$("#current_id").val();
						   console.debug(sub_currentId);
						   console.debug($("#code_"+sub_currentId));
						   $("#code_"+sub_currentId).val(code);
						   product.Plan.getBom(code,ctx);
					   });
				   }
			   }
		   }
	   });
};
product.Plan.datepicker = function(datepicker){
	var dayNames=["周日","周一","周二","周三","周四","周五","周六"];
	var monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];

	$(datepicker).datepicker({
		dateFormat:"yy-mm-dd",
		autoSize:true,
		dayNamesMin:dayNames,
		monthNames:monthNames
	});
};
product.Plan.addDetail = function(){
	var $detailContainer = $("#detail_container"),
		$currentId = $("#current_id"),
		currentId=0;
	if($currentId!==undefined){
		try{
		currentId=parseInt($currentId.val());
		}catch(e){
			currentId = 0;
		}
	}
	var code="";
	
	if(arguments[0]!==undefined){
		code=arguments[0];
	}
	if(currentId==0){
		currentId=1;
	}else{
		currentId=currentId+1;
	}
	$currentId.val(currentId);
	
	var detailTemplate = template("plan_detail",{id:currentId,code:code});
	$detailContainer.append(detailTemplate);
	product.Plan.autoModel(".autocomplete");
	product.Plan.datepicker(".datepicker");
	
	return false;
};
product.Plan.delDetail = function(id){
	var content = $("#"+id);
	if(content!==undefined){
		content.remove();
	}
	return false;
};
product.Plan.submit = function(){
	$("#plan-submit").on("click",function(){
		$("#form-data").on("submit",function(){
			//console.debug("submit");
			var currentId = $("#current_id").val();
			//console.debug(currentId);
			if(currentId>0){
				for(var index=1;index<=currentId;index++){
					var $needTotal = $("#needTotal_"+index);
					if($needTotal!==undefined){
						var needTotal = $needTotal.val();
						//console.debug(needTotal==0);
						if(needTotal<0){
							alert("请填写需要生产的数量！");
							return false;
						}
					}
				}
			}
			return true;
		});
		
	});
};

product.Plan.init = function(){
	$("#add_detail").on("click",function(){
		product.Plan.addDetail();
	});
	
	product.Plan.autoModel(".autocomplete");
	product.Plan.datepicker(".datepicker");
	product.Plan.submit();
};

product.Plan.Detail={};
product.Plan.Detail.initGrid = function(id,stations){
	var options = {},
        colNames = ["","序号","计划号","订单日期","规格型号","描述","长度","单位","工位","完成日期","状态","备注"];
        colModel = [
        {name:"myac",fixed:true,width:80,formatter:"actions",formatoptions:{keys:true}},
        {name:"id",index:"id",width:10,key:true},
        {name:"planCode",index:"planCode",width:25},
        {name:"createDate",index:"createDate",width:22},
        {name:"materialModel",index:"model",width:35},
        {name:"materialDesc",index:"materialDesc",width:10},
        {name:"needTotal",index:"needTotal",width:15},
        {name:"unit",index:"unit",width:10},
        {name:"stationName",index:"stationId",width:25,editable:true,edittype:"select"
        	,editoptions:{
        		value:stations
        		   }},
        {name:"finishDate",index:"finishDate",width:22},
        {name:"statusMessage",index:"status",width:25},
        {name:"memo",index:"memo",width:25,editable:true}
    ];
    var jsonUrl = "getJson.jspx";
    if(id!==0){
    	jsonUrl = jsonUrl + "?id="+id;
    }
    options = {colNames:colNames,
               colModel:colModel,
               jsonUrl:jsonUrl
               ,processUrl:"process.jspx?format=json"
               ,canEdit:false,
               canAdd:false,
               canDel:false,
               loadComplete:product.Plan.Detail.loadComplete,
               caption:"生产计划详情列表"};
    
    customGrid.init(options);
};
product.Plan.Detail.loadComplete = function(table){
	var trs = $(table).find('tr');
	if(trs!==undefined){
		trs.each(function(index,tr){
			//console.log(tr);
			var id = $(tr).attr('id');
			if(id!==undefined){
				var children = $(tr).children();
				//console.log(children);
				if(children!==undefined){
					children.each(function(index,child){
						var fieldName = $(child).attr('aria-describedby');
						var title = $(child).attr('title');
						if(fieldName==='gridTable_statusMessage'){
							if(title==='未确认' || title==='未分配'){
								
							}else
							{
								$('#jEditButton_'+id).css('display','none');
								$('#jDeleteButton_'+id).css('display','none');
							}
						}
					});
				}
			}
		});
	}
	
};
product.Plan.Detail.init = function(){
	$.get("getInfo.jspx?format=json",function(data){
		if(data!==undefined){
			var $stationid = $("#stationid");
			$stationid.empty();
			var stations = data.stations;
			if(stations!==undefined){
				$.each(stations,function(index,station){
					$stationid.append('<option value="'+station.id+'">'+station.name+'</option>');
				});
			}
		}
	});
};

product.ProductTask={};
product.ProductTask.init = function(options){
	product.ProductTask.initData();
	
	setInterval(product.ProductTask.doTask,60000);
	
};
product.ProductTask.initData=function(){
	product.ProductTask.getPlanDetails();
	product.ProductTask.getProductTask("NoMaterial");
	product.ProductTask.getProductTask("NoProduct");
	product.ProductTask.getProductTask("Producting");
}
var taskIndex = 1;
product.ProductTask.doTask = function(){
	if(taskIndex==5){
		taskIndex=1;
	}
	if(taskIndex==1){
	    product.ProductTask.getPlanDetails();
	}else if(taskIndex==2){
	   product.ProductTask.getProductTask("NoMaterial");
	   
	}else if(taskIndex==3){
	   product.ProductTask.getProductTask("NoProduct");
	}else{
	   product.ProductTask.getProductTask("Producting");
	}
	taskIndex++;
	
}
/*获取计划详情*/
product.ProductTask.getPlanDetails = function(){
	$.get("getPlanDetails.jspx",{format:"json"},function(data){
		if(data!==undefined && data.hasError===false){
			var $tableConfirm = $("#table-noconfirm");
			$tableConfirm.empty();
			var tableTemplate = template("template-noconfirm",data);
			$tableConfirm.append(tableTemplate);
			$("#badge-noconfirm").html(data.count);
		}else{
			var $alertMessage = $('#alert-message');
			//$alertMessage.empty();
			
			var alertTemplate = template('alert-template',data);
			$alertMessage.append(alertTemplate);
		}
	});
};
/*获取工艺卡*/
product.ProductTask.getProductTask = function(status){
	$.get("getProductTasks.jspx",{format:"json",status:status},function(data){
		if(data!==undefined && data.hasError===false){
			status = status.toLowerCase();
			var $tableConfirm = $("#table-"+status);
			$tableConfirm.empty();
			var tableTemplate = template("template-"+status,data);
			$tableConfirm.append(tableTemplate);
			$("#badge-"+status).html(data.count);
			if('nomaterial'==status){
			   product.ProductTask.applyAll();
			}
		}else{
			var $alertMessage = $('#alert-message');
			//$alertMessage.empty();
			
			var alertTemplate = template('alert-template',data);
			$alertMessage.append(alertTemplate);
			
			
		}
	});
};
//确认计划详情
product.ProductTask.confirm = function(id,ctx){
	var result = confirm("是否要确定此计划？");
	if(result){
		if(id!==undefined && id>0){
			$.get("confirm.jspx",{id:id,format:"json"},function(data){
				if(data!==undefined && data.hasError==true){
					alert(data.message);
				}else{
					product.ProductTask.getPlanDetails();
					product.ProductTask.getProductTask("NoMaterial");
				}
				$.get(ctx+"/report/log/addLog.jspx",{format:"json",m:"确认"+id+"号任务",c:"004"},function(data){
					
				});
			});
			
		}
	}else{
		$.get(ctx+"/report/log/addLog.jspx",{format:"json",m:"取消任务确认",c:"004"},function(data){
			
		});
	}
};

product.ProductTask.applyAll = function(){
	
	$('#apply_all').on('click',function(){
		var checked = $(this).prop('checked');
		var checkboxs = $('input[name=apply_taskid]');
		if(checkboxs!==undefined && checkboxs.length>0){
			$.each(checkboxs,function(index,checkbox){
				if(!$(checkbox).prop('disabled')){
					$(checkbox).prop('checked',checked);
				}
			});
		}
	});
};
//申请原材料
/*
 * 5-16 修改为多条记录同时申请
 * 
 * 
 * */
product.ProductTask.applyMaterial = function(id,ctx){
	var result = confirm("确定要申请物料吗？");
	if(result){
		if(id!==undefined && id>0){
			var $taskIds = $('input[name=apply_taskid]:checked'),
			    taskIdArray = [id],
			    taskIds = "";
			if($taskIds!==undefined && $taskIds.length>0){
				$.each($taskIds,function(index,element){
					taskIdArray.push($(element).val());
				});
				//console.log(taskIdArray);
				taskIds = taskIdArray.join(',');
			}else{
				taskIds=id;
			}
			//console.log(taskIds);
			$("#taskIds").val(taskIds);
			$.get("applyMaterial.jspx",{id:id,taskIds:taskIds,format:"json"},function(data){
				if(data!==undefined && data.hasError==true){
					alert(data.message);
				}else{
					$("#apply_count").val(data.applyCount);
					//product.ProductTask.getPlanDetails();
					var template_materials_body = template("template-materials-body",data);
					$("#materials-body").empty().append(template_materials_body);
					$("#stack-out-modal").modal('show');
				}
			});
			if(taskIds!=""){
				product.addLog("申请"+taskIds+"号计划物料","005",ctx);
			}else{
				product.addLog("申请"+id+"号计划物料","005",ctx);
			}
			
		}
	}else{
		product.addLog("申请计划物料取消","005",ctx);
	}
};
product.ProductTask.submitApply = function(ctx){
	var result = confirm("确定提交物料出库申请吗?");
	if(result){
		var $form=$("#material_stock_out_form");
		var requestData = $form.formSerialize();
		$.get('submitApply.jspx?format=json&'+requestData,function(data){
			if(data!==undefined && data.hasError){
				alert(data.message);
			}else{
				$("#stack-out-modal").modal("hide");
				$("#stock_out_task_id").val(0);
				product.ProductTask.getProductTask("NoMaterial");
			}
		});
		product.addLog("提交物料申请","005",ctx);
	}else{
		product.addLog("取消提交物料申请","005",ctx);
	}
};
/*显示申请原材料结果*/
product.ProductTask.showApply = function(id){
	if(id!==undefined && id>0){
		$("#return_stock_out_card_id").val(id);
		$.get("showStockOuts.jspx",{format:"json",id:id},function(data){
			if(data!==undefined){
				var template_data = template("return-template-materials-body",data);
				$("#return-materials-body").empty().append(template_data);
				$("#return-stack-out-modal").modal();
			}
		});
	}
};
product.ProductTask.confirmApply = function(ctx){
	
	var result = confirm("确定物料返回的信息吗?");
	if(result){
		$("#show_material_stock_out_form").on("submit",function(){
			var options = {
				success:function(data){
					if(data!==undefined && data.hasError){
						alert(data.message);
					}else{
						$("#return-stack-out-modal").modal("hide");
						product.ProductTask.getProductTask("NoMaterial");
						product.ProductTask.getProductTask("NoProduct");
					}
				}	
			};
			$(this).ajaxSubmit(options);
			
			return false;
		});
		product.addLog("确定物料返回信息","005",ctx);
	}else{
		product.addLog("取消确定物料返回信息","005",ctx);
	}
	
};

product.ProductTask.showProperties = function(ctx,process,materialCode,destCode){
	$.get(ctx+'/repo/bom/getProperties.jspx?format=json',{process:process,materialCode:materialCode,destCode:destCode},function(data){
		if(data!==undefined){
			var $header = $('#properties_header'),
			    $body=$('#properties_body');
			$header.empty();
			$body.empty();
			if(process==='绝缘' || process==='护套'){
				var headerTemplate = template('header1'),
				    bodyTemplate = template('body1',data);
				$header.append(headerTemplate);
				$body.append(bodyTemplate);
			}else{
				var headerTemplate = template('header2'),
			    bodyTemplate = template('body2',data);
			    $header.append(headerTemplate);
			    $body.append(bodyTemplate);
			}
			$('#properties-show-modal').modal();
		}
	});
};

product.ProductTask.finish = function(id){
	var result = confirm("确定完成此任务生产吗？");
	if(result){
		$.post("changeStatus.jspx",{format:"json",id:id,status:"Finished"},function(data){
			if(data!==undefined && !data.hasError){
				product.ProductTask.getProductTask("Producting");
			}
		});
	}
};

product.ProductTask.showFinished = function(options){
	$('#finished_year').val(options.currentYear);
	 $('#finished_month').val(options.currentMonth);
	 $('#finished_day').val(options.currentDay);
	 
	var colNames = ["序号","计划号","任务号","规格型号","描述","开始时间","完成时间","总共用时","完成数量","单位"];
	    colModel = [
		    {name:"id",index:"id",width:55,fixed:true,key:true},
		    {name:"planDetail.planCode",index:"planCode",width:20},
		    {name:"code",index:"code",width:20},
		    {name:"planDetail.materialModel",index:"materialModel",width:30},
		    {name:"planDetail.materialDesc",index:"materialDesc",width:8},
		    {name:"starttime",index:"startTime",width:18},
		    {name:"finishtime",index:"finishTime",width:18},
		    {name:"countTime",index:"countTime",width:10},
		    {name:"finalTotal",index:"finalTotal",width:8},
		    {name:"planDetail.unit",index:"unit",width:8}
		];
	 var options = {
		colNames:colNames,
		colModel:colModel,
		canAdd:false,
		canEdit:false,
		canDel:false,
		jsonUrl:options.jsonUrl
	 };
	 customGrid.init(options);

	 $('#finished_button').on('click',function(data){
		 var year = $('#finished_year').val(),
		     month = $('#finished_month').val(),
		     day = $('#finished_day').val(),
		     jsonUrl = 'getFinished.jspx?format=json&year='+year+'&month='+month+'&day='+day;
		 customGrid.reload({url:jsonUrl});
	 });
	 
	 $('#finished_year').on('change',function(){
		 product.ProductTask.initDays($(this).val(),$('#finished_month').val());
	 });
	 
	 $('#finished_month').on('change',function(){
		 product.ProductTask.initDays($('#finished_year').val(),$(this).val());
	 });
};
product.ProductTask.initDays=function(year,month){
	if(year>0 && month>0){
		var days = new Date(year,month,0).getDate();
		var $day = $('#finished_day');
		$day.empty();
		$day.append('<option ="0">全部</option>');
		for(var day=1;day<=days;day++){
			$day.append('<option ="'+day+'">'+day+'</option>');
		}
	}
};
product.ProductTask.start = function(id){
	var result = confirm("确定开始生产吗？");
	if(result){
		$.post("changeStatus.jspx",{format:"json",id:id,status:"Producting"},function(data){
			if(data!==undefined && !data.hasError){
				product.ProductTask.getProductTask("NoProduct");
				product.ProductTask.getProductTask("Producting");
			}
		});
    }
};

product.ProductTask.showProblem = function(id){
	$("#product_task_id").val(id);
	$("#product-problem-modal").modal();
};
product.ProductTask.problem=function(){
	var id = $("#product_task_id").val();
	var memo = $("#memo").html();
	$.post("changeStatus.jspx",{format:"json",id:id,status:"ShortError"},function(data){
		if(data!==undefined && !data.hasError){
			product.ProductTask.getProductTask("Producting");
			product.addLog("生产计划："+id+" 备注："+memo,"009");
			$("#product-problem-modal").modal("hide");
		}
	});
};
product.ProductTask.continueProducting=function(id){
	$.post("changeStatus.jspx",{format:"json",id:id,status:"Producting"},function(data){
		if(data!==undefined && !data.hasError){
			product.ProductTask.getProductTask("NoProduct");
			product.ProductTask.getProductTask("Producting");
			product.addLog(id+"恢复生产","009");
		}
	});
};
product.ProductTask.returnStock=function(){
	var id = $("#product_task_id").val();
	var memo = $("#memo").html();
	$.post("changeStatus.jspx",{format:"json",id:id,status:"Finished"},function(data){
		if(data!==undefined && !data.hasError){
			product.ProductTask.getProductTask("Producting");
			$("#product-problem-modal").modal("hide");
			product.addLog(id+"返库完成 备注："+memo,"008");
		}
	});
	
};